<template>
  <div class='container'>
        <el-form
          ref="form"
          :model="formData"
          :rules="rules"
          label-position="left"
          label-width="100px"
          style="width: 80%; margin-left:10px;"
        >
          <el-form-item label="学科名称" prop="subjectName">
            <el-input v-model="formData.subjectName"></el-input>
          </el-form-item>
          <el-form-item label="是否显示" prop="isFrontDisplay">
            <el-switch
            v-model="formData.isFrontDisplay"
            active-value=1
            inactive-value=0
            ></el-switch>
          </el-form-item>
          <el-form-item class="right">
            <el-button  @click="$emit('close')">取消</el-button>
            <el-button  type="primary" @click="doSave">确认</el-button>
          </el-form-item>
        </el-form>
  </div>
</template>

<script>
import { add, detail, update } from '@/api/hmmm/subjects'
export default {
  name: 'SubjectAddOrEdit',
  props: {
    currentData: {
      type: Object,
      default: null // 这个属性并不是必须的
    }
  },
  data () {
    return {
      formData: {
        id: '',
        subjectName: '',
        isFrontDisplay: ''
      },
      rules: {
        subjectName: [{ required: true, message: '请输入活动名称', trigger: 'blur' }]
      }
    }
  },
  created () {
    // 判断有无ID传过来，有就执行获取详情方法
    if (this.currentData) {
      this.loadDetail()
    }
  },
  methods: {
    // 发送添加的请求
    handleAdd () {
      add(this.formData)
    },
    // 兜底检验，检验成功执行添加请求
    doSave () {
      this.$refs.form.validate(async valid => {
        if (valid) {
          // 判断有无id,有执行更新函数，无执行新增函数
          await this.currentData ? this.doUpdate() : this.handleAdd()
          await this.$message.success(this.currentData ? '修改数据成功' : '添加数据成功')
          this.emit()
        }
      })
    },
    // 关闭弹窗并刷新页面的方法
    emit () {
      // this.$listeners: 自动会收集所有加在这个组件上的事件监听
      this.$listeners.close && this.$emit('close')
      this.$listeners.refresh && this.$emit('refresh')
    },
    // 获取学科详情方法
    async loadDetail () {
      const res = await detail(this.currentData)
      console.log(res)
      // 数据解构
      const { id, subjectName, isFrontDisplay } = res.data
      this.formData = {
        id,
        subjectName,
        isFrontDisplay: isFrontDisplay.toString()
      }
    },
    // 发送更新数据的请求
    async doUpdate () {
      await update(this.formData)
    }
  }
}
</script>

<style  lang="scss" scoped>
.right{
  display: flex;
  justify-content: flex-end;
}
</style>
